package com.example.administrator.szb.fragments.fragment_forTW;

import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.example.administrator.szb.R;
import com.example.administrator.szb.adapter.BaseAdapter;
import com.example.administrator.szb.adapter.MyOnScroll;
import com.example.administrator.szb.fragments.base.BaseFragment;
import com.example.administrator.szb.bean.ColorBean;
import com.example.administrator.szb.bean.StarBean;
import com.example.administrator.szb.bean.ZDYHBean;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.GetJsonDataUtil;
import com.example.administrator.szb.util.SharedPreferencesUtil;
import com.example.administrator.szb.util.Toasts;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by D N on 2017/9/25.
 */

public class FragmentZDYH extends BaseFragment {
    View view;
    String param = "0";
    int type = 0;
    int current_page = 1;
    int per_page = 10;
    @Bind(R.id.zdyh_framelayout_load)
    LinearLayout zdyhFramelayoutLoad;
    @Bind(R.id.zdyh_recyclerview)
    RecyclerView zdyhRecyclerview;

    BaseAdapter<ZDYHBean.DataBeanX.DataBean> adapter;
    ArrayList<ZDYHBean.DataBeanX.DataBean> mdata = new ArrayList<>();
    ZDYHBean zDYHBean;//实体类用于填充数据
    private ArrayList<View> starts = new ArrayList<>();//星星图标的集合
    private View footerview;//加载更多

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_zdyh, container, false);
        footerview = LayoutInflater.from(getActivity()).inflate(R.layout.view_wd_footer, null);
        footerview.setVisibility(View.INVISIBLE);
        getParam();
        ButterKnife.bind(this, view);
        requestZDYH();
        return view;
    }

    private void getParam() {
        param = getArguments().getString("param");

        try{
            type = getArguments().getInt("type");
        }catch (Exception e){
            e.toString();
        }
    }

    /**
     * 执行数据请求
     */
    private void requestZDYH() {
        HashMap<String, String> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("param", param);
        map.put("id", SampleApplicationLike.getUserloginInstance().getId() + "");
       // map.put("id","51");
        map.put("type", type + "");
        map.put("per_page", per_page + "");
        map.put("current_page", current_page + "");

        String url =  URLAddress.URLBASE + URLAddress.URL_CROWD;
        String json = GetJsonDataUtil.simpleMapToJsonStr(map);
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST,ZDYHBean.class, URLAddress.URLBASE + URLAddress.URL_CROWD, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                 zDYHBean = (ZDYHBean) response;
                if (zDYHBean.getResult() == 1 && zDYHBean.getData().getData() !=null && current_page == 1) {
                    mdata.addAll(zDYHBean.getData().getData());
                    current_page = current_page + 1;
                    initView();//渲染数据
                    zdyhFramelayoutLoad.setVisibility(View.GONE);
                }else if(zDYHBean.getResult() == 1&& zDYHBean.getData().getData() !=null){
                    current_page = current_page + 1;
                    mdata.addAll(zDYHBean.getData().getData());
                    adapter.notifyDataSetChanged();
                    footerview.setVisibility(View.INVISIBLE);
                    zdyhFramelayoutLoad.setVisibility(View.GONE);
                    if ( zDYHBean.getData().getData().size() == 0){
                       // Toasts.show(getActivity(), "没有数据啦", Toast.LENGTH_SHORT);
                    }
                }

                else{
                    Toasts.show(getActivity(), "没有数据哦", Toast.LENGTH_SHORT);
                    zdyhFramelayoutLoad.setVisibility(View.GONE);
                    footerview.setVisibility(View.INVISIBLE);
                }
            }


        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.toString();
            }
        });
    }

    private void initView() {

        zdyhRecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
        initAdapter();//初始化adapter
        adapter.addFootView(footerview);
        zdyhRecyclerview.setAdapter(adapter);
        loadMore();
    }
    /**
     * 开启加载更多
     */
    private void loadMore() {

        zdyhRecyclerview.addOnScrollListener(new MyOnScroll(){
            @Override
            public void scrollBottom() {

                super.scrollBottom();
                footerview.setVisibility(View.VISIBLE);
                requestZDYH();
            }
        });
    }

    private void initAdapter() {
        try {
            adapter = new BaseAdapter<ZDYHBean.DataBeanX.DataBean>(getActivity(),mdata) {
                @Override
                public void convert(int position, BaseViewHolder holder, ZDYHBean.DataBeanX.DataBean dataBean) {
                    initItem(holder,dataBean);//填充数据
                }

                @Override
                public int getLayoutId(int viewType) {
                    return R.layout.view_zdyh_item;
                }
            };
        }catch (Exception e){
            Toasts.show(getActivity(), "暂无数据哦。。。", Toast.LENGTH_SHORT);
        }



    }

    private void initItem(BaseAdapter<ZDYHBean.DataBeanX.DataBean>.BaseViewHolder holder, final ZDYHBean.DataBeanX.DataBean dataBean) {
        if (!TextUtils.isEmpty(dataBean.getHead_img())) {
            Glide.with(getActivity()).load(dataBean.getHead_img()).into((ImageView) (holder).getView(R.id.imageView20));
        }

        if (!TextUtils.isEmpty(dataBean.getName())){
            ((TextView) holder.getView(R.id.textView49)).setText(dataBean.getCompany() + "-" + dataBean.getName());
        }else{
            ((TextView) holder.getView(R.id.textView49)).setText(dataBean.getCompany());
        }

        if (dataBean.getCompany() == null){
            ((TextView)holder.getView(R.id.textView50)).setVisibility(View.INVISIBLE);
        }else{
            ((TextView)holder.getView(R.id.textView50)).setVisibility(View.INVISIBLE);
            //((TextView)holder.getView(R.id.textView50)).setText(dataBean.getCompany());
        }
        if (dataBean.getDescription() == null){
            ((TextView)holder.getView(R.id.textView51)).setVisibility(View.INVISIBLE);
        }else {
            ((TextView)holder.getView(R.id.textView51)).setText((String)dataBean.getCity());
        }


        /**
         * 显示业务标签
         */

        showYW(dataBean,holder);

        /**
         * 显示星星
         */
        showStar(dataBean,holder);

        ((CheckBox)holder.getView(R.id.checkBox)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b){
                   // AskActivity.choose_list.add(dataBean);
                }else {
                    //AskActivity.choose_list.remove(dataBean);
                }
            }
        });


    }

    private void showStar(final ZDYHBean.DataBeanX.DataBean dataBean, BaseAdapter.BaseViewHolder holder) {
        final ArrayList<StarBean> mdata = new ArrayList<>();
        RecyclerView recyclerView = ((RecyclerView) holder.getView(R.id.zdyh_recyclerview_star));
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 5));
        for (int i = 0; i < 5; i++) {
            StarBean b = new StarBean();
            mdata.add(b);
        }
        BaseAdapter<StarBean> adapter = new BaseAdapter<StarBean>(getActivity(),mdata) {
            @Override
            public void convert(int position, BaseViewHolder holder, StarBean starBean) {
                ((ImageView) holder.getView(R.id.view_zdyh_star)).setImageResource(R.drawable.star_hui);
                if (dataBean.getEvaluate() / 2 > position){
                    ((ImageView) holder.getView(R.id.view_zdyh_star)).setImageResource(R.drawable.start);
                }
                if (position == dataBean.getEvaluate() / 2 + dataBean.getEvaluate() % 2 - 1 && dataBean.getEvaluate() % 2 != 0) {
                    ((ImageView) holder.getView(R.id.view_zdyh_star)).setImageResource(R.drawable.star_half);
                }
            }

            @Override
            public int getLayoutId(int viewType) {
                return R.layout.view_zdyh_star;
            }
        };
        recyclerView.setAdapter(adapter);
    }

    private void showYW(ZDYHBean.DataBeanX.DataBean dataBean, BaseAdapter.BaseViewHolder holder) {

        RecyclerView recyclerView = ((RecyclerView)holder.getView(R.id.zdyh_recyclerview_ywbq));
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),4));
        BaseAdapter<ZDYHBean.DataBeanX.DataBean.BusinessBean> adapter = new BaseAdapter<ZDYHBean.DataBeanX.DataBean.BusinessBean>(getActivity(),dataBean.getBusiness(),4) {
            @Override
            public void convert(int position, BaseViewHolder holder, ZDYHBean.DataBeanX.DataBean.BusinessBean businessBean) {
                GradientDrawable drawable;
                ((TextView) holder.getView(R.id.view_jgxq_text)).setText(businessBean.getTitle());
                try {
                    Class<?> c = null;
                    c = Class.forName("bean.ColorBean$DataBean");
                    ColorBean.DataBean obj = (ColorBean.DataBean) c.newInstance();
                    //第一个参数写的是方法名,第二个\第三个\...写的是方法参数列表中参数的类型
                    Method method=c.getMethod("get_$"+businessBean.getId());
                    ColorBean colorbean = (ColorBean) SharedPreferencesUtil.getData(getActivity(),"yw_color");
                    String str2 = (String) method.invoke(colorbean.getData());


                    drawable = (GradientDrawable)  ((TextView) holder.getView(R.id.view_jgxq_text)).getBackground();
                    drawable.setColor(Color.parseColor(str2));
                }catch (Exception e){

                }


            }

            @Override
            public int getLayoutId(int viewType) {
                return R.layout.view_jgxq_item;
            }
        };
        recyclerView.setAdapter(adapter);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
